const initialState = {
  suggests: [] as string[],
  resultMap: {} as IResultMap,
};

export type ActionType =
  | { type: 'search/saveSuggests'; payload: string[] }
  | { type: 'search/saveResults'; payload: IResultMap }
  // 1. 扩展ActionType的类型
  | { type: 'search/clearResults' };

function searchReducer(state = initialState, action: ActionType): typeof initialState {
  switch (action.type) {
    case 'search/saveSuggests':
      return {
        ...state,
        suggests: action.payload,
      };
    case 'search/saveResults':
      const oldList = state.resultMap.results || [];
      const newList = [...oldList, ...action.payload.results];
      return {
        ...state,
        resultMap: {
          ...action.payload,
          results: newList,
        },
      };
    // 2. 完成清除的逻辑
    case 'search/clearResults':
      return {
        ...state,
        resultMap: {} as IResultMap,
      };

    default:
      return state;
  }
}

export default searchReducer;

interface IResultMap {
  page: number;
  per_page: number;
  results: IResult[];
  total_count: number;
}

export interface IResult {
  art_id: string;
  title: string;
  aut_id: string;
  aut_name: string;
  comm_count: number;
  pubdate: string;
  cover: ICover;
  like_count: number;
  collect_count: number;
}

interface ICover {
  type: number;
  images?: string[];
}
